import { history } from 'ice';
import { Message } from '@alifd/next';
import userService from '@/services/user';
import cookie from 'react-cookies';

export default {
  state: {
    current: [],
    user: [],
    users: [],
    captcha: '',
  },
  reducers: {
    update: (prevState, payload) => {
      return { ...prevState, ...payload };
    },
  },
  effects: (dispatch) => ({
    fetchUsers: async (params) => {
      const data = await userService.getUsers(params);
      if (data.code === 0) {
        dispatch.user.update({ users: data.page });
      } else {
        Message.error(data.msg);
      }
    },
    fetchCaptcha: async (params) => {
      const data = await userService.captcha(params);
      if (typeof data === 'string') {
        dispatch.user.update({ captcha: data });
      } else {
        Message.error(data.msg);
      }
    },
    fetchLogin: async (data) => {
      const res = await userService.login(data);
      if (res.code === 0) {
        Message.success({
          content: '登录成功！',
          hasMask: true,
          afterClose: () => {
            cookie.save('token', res.token, { maxAge: res.expire });
            history.push('/');
          },
        });
      } else {
        Message.error(res.msg);
      }
    },
    fetchUser: async (userId) => {
      const data = await userService.getUser(userId);
      if (data.code === 0) {
        dispatch.user.update({ user: data.user });
      } else {
        Message.error(data.msg);
      }
    },
    fetchCurrent: async () => {
      const data = await userService.getCurrent();
      if (data.code === 0) {
        dispatch.user.update({ current: data.user });
      } else {
        Message.error(data.msg);
      }
    },
    createUser: async (data) => {
      const res = await userService.addUser(data);
      if (res.code === 0) {
        Message.success({
          content: res.msg,
          hasMask: true,
        });
      } else {
        Message.error({
          content: res.msg,
          hasMask: true,
        });
      }
    },
    updateUser: async (data) => {
      const res = await userService.updateUser(data);
      if (res.code === 0) {
        Message.success({
          content: '编辑成功！',
          hasMask: true,
        });
      } else {
        Message.error({
          content: res.msg,
          hasMask: true,
        });
      }
    },
    delUsers: async (ids) => {
      const res = await userService.delUsers(ids);
      if (res.code === 0) {
        Message.success({
          content: '删除成功！',
          hasMask: true,
        });
      } else {
        Message.error({
          content: res.msg,
          hasMask: true,
        });
      }
    },
  }),
};
